package healthwatcher.data.gae;

import javax.jdo.PersistenceManager;

import healthwatcher.data.IEmployeeRepository;
import healthwatcher.model.employee.Employee;
import lib.exceptions.ObjectAlreadyInsertedException;
import lib.exceptions.ObjectNotFoundException;
import lib.exceptions.ObjectNotValidException;
import lib.exceptions.RepositoryException;
import lib.persistence.IPersistenceMechanism;

public class EmployeeRepositoryGAE implements IEmployeeRepository {

	private IPersistenceMechanism mp;


	public EmployeeRepositoryGAE(IPersistenceMechanism mp) {
		this.mp = mp;
	}
	
	@Override
	public void insert(Employee employee) throws ObjectNotValidException,
			ObjectAlreadyInsertedException, ObjectNotValidException,
			RepositoryException {
		
		PersistenceManager pm = (PersistenceManager) mp.getCommunicationChannel();
		pm.makePersistent(employee);
		
	}

	@Override
	public void update(Employee employee) throws ObjectNotValidException,
			ObjectNotFoundException, ObjectNotValidException,
			RepositoryException {
		
		try {
			insert(employee);
		} catch (ObjectAlreadyInsertedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public boolean exists(String login) throws RepositoryException {
		
		try {
			
			Employee employee = search(login);
			
			if(employee != null)
				return true;
			else return false;
			
		} catch (ObjectNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	@Override
	public void remove(String login) throws ObjectNotFoundException,
			RepositoryException {

		PersistenceManager pm = (PersistenceManager) mp.getCommunicationChannel();
		Employee employee = pm.getObjectById(Employee.class,login);
		pm.deletePersistent(employee);
		
	}

	@Override
	public Employee search(String login) throws ObjectNotFoundException,
			RepositoryException {

		PersistenceManager pm = (PersistenceManager) mp.getCommunicationChannel();
		Employee employee = pm.getObjectById(Employee.class,login);
		pm.close();
		return employee;
	}

}
